<!-- 房屋管理 -->
<template>
  <div>
    <div class="header">
      <div class="title" style="height: 65px">
        <div style="margin-bottom: 5px; margin-top: 5px">
          <a-space style="margin-top: 15px; margin-left: 15px">
            <span>任务名称：</span>
            <a-input
              v-model:value="txtKeyWord"
              placeholder="请输入任务名称进行查询"
              style="width: 256px; margin-top: -10px"
            />
          </a-space>
          <a-space style="margin-top: 15px; margin-left: 25px">
            <span>任务轮次：</span>
            <a-select ref="select" v-model:value="selectpc" style="width: 120px">
              <a-select-option value="第一轮">第一轮</a-select-option>
              <a-select-option value="第二轮">第二轮</a-select-option>
              <a-select-option value="第三轮">第三轮</a-select-option>
            </a-select>
          </a-space>
           
          &nbsp;&nbsp;&nbsp;&nbsp;
          <a-space class="search-btn">
            <a-button type="primary" @click="searchBtn">查询</a-button>
          </a-space>
           <a-space style="margin-top: 15px; margin-left: 25px">
            <a-button type="primary" @click="btnTaskXZ"  v-if="isShowXZ" >双通道不合格销账情况</a-button>
          </a-space>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <a-space type="primary" size="small" style="float: right; margin-right: 10px; margin-top: 15px">
               <a-button type="primary" @click="handleHourseExport">导出已核验明细</a-button>
          </a-space>
          <a-space class="search-btn"  style="float: right; margin-right: 20px;margin-top: 20px">
            <a-checkbox v-model:checked="checked" >重点村</a-checkbox>
          </a-space>
          &nbsp;&nbsp;&nbsp;&nbsp;
<a-space style="float: right; margin-right: 20px; margin-top: 15px">
  <span>核验结束时间：</span>
  <a-date-picker v-model:value="endDate" :format="dateFormat" :disabledDate="disabledFutureDate"  />
</a-space>
          <a-space style="float: right; margin-right: 30px; margin-top: 15px">
  <span>核验开始时间：</span>
  <a-date-picker v-model:value="startDate" :format="dateFormat" :disabledDate="disabledFutureDate"  />
</a-space>


        </div>
      </div>
      <div style="width: 100%; background: #fff; height: 40px">
        <div
          style="width: 7%; float: right; font-size: 16px; padding-left: 20px; line-height: 37px"
        >
          <a-space class="search-btn">
            <a-button type="primary" size="small" @click="showModal"   v-if="isShowButton" >添加抽检任务</a-button>
          </a-space>
        </div></div
      >
      <a-table
        :dataSource="tableData"
        :columns="displayColumns"
        :pagination="false"
        :scroll="{ x: 1500, y: detailTableHeight }"
        bordered
        :loading="loading"
      />
      <!-- 添加抽样 -->
      <a-modal
        ref="modalRef"
        v-model:visible="taskopen"
        :modal-style="{ top: '20%', transform: 'translateY(-20%)' }"
        :auto-adjust="false"
        :wrap-style="{ overflow: 'hidden' }"
        @ok="handleOk"
      >
        <template #footer>
          <a-button key="back" @click="handleOk">取消</a-button>
          <a-button key="submit" type="primary" :loading="loading" @click="validateForm"
            >保存</a-button
          >
        </template>
        <a-form
          ref="formRef"
          :model="formState"
          :label-col="{ span: 6, offset: 2 }"
          :wrapper-col="wrapperCol"
          :rules="rules"
          style="padding: 30px 0px"
        >
          <a-form-item label="选择轮次" name="taskpch">
            <a-select
              v-model:value="formState.taskpch"
              placeholder="请选择轮次"
              style="width: 280px"
              @change="onChangePch"
            >
              <a-select-option v-for="item in pchList" :key="item.pch" :value="item.pch">
                {{ item.pch }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="任务名称" name="taskname">
            <a-input v-model:value="formState.taskname" />
          </a-form-item>
          <a-form-item label="抽检地区" name="taskregion">
            <a-space style="margin-top: -14px; position: absolute">
              <a-input-group compact>
                <a-cascader
                  v-model:value="formState.taskregion"
                  style="width: 280px"
                  :options="regionList"
                  expand-trigger="hover"
                  placeholder="请选择抽检地区"
                  changeOnSelect
                  @change="onChange"
                />
              </a-input-group>
            </a-space>
          </a-form-item>
          <!--<a-form-item label="抽检层数" name="cqcs">
            <a-checkbox-group v-model:value="formState.cqcs" @change="handleChange">
              <a-checkbox value="1" name="type" >一层</a-checkbox>
              <a-checkbox value="2" name="type" >二层</a-checkbox>
              <a-checkbox value="3" name="type" >三层及以上</a-checkbox>
            </a-checkbox-group>
          </a-form-item>-->
          <a-form-item label="房屋总数量">
            <span style="font-weight: bold; color: red; display: block; text-align: center"
              >{{ formState.fwzcount }} (含{{ formState.twofwzcount }}栋2层以上)</span
            >
          </a-form-item>

          <a-form-item label="可抽检房屋数">
            <span style="font-weight: bold; color: red; display: block; text-align: center"
              >{{ formState.fwcount }} (含{{ formState.twofwcount }}栋2层以上)</span
            >
          </a-form-item>
          <a-form-item label="抽检房屋比例" name="cqbl">
            <a-input-number
              v-model:value="formState.cqbl"
              :min="0"
              :max="100"
              style="width: 280px"
              :formatter="(value) => `${value ?? 0}%`"
              :parser="(value) => parseFloat(value.replace('%', ''))"
              @change="handleInput"
            />
          </a-form-item>
          <a-form-item label="抽检房屋数" name="cqcount">
            <a-input-number
              v-model:value="formState.cqcount"
              :min="0"
              :max="formState.fwcount"
              style="width: 280px"
              @change="handleInput2"
            />
          </a-form-item>
          <a-form-item label="剩余房屋数">
            <span style="font-weight: bold; color: red; display: block; text-align: center">{{
              formState.sycount
            }}</span>
          </a-form-item>
          <a-form-item label="任务指派至" name="zname">
            <a-select
              v-model:value="formState.zname"
              placeholder="请选择人员"
              style="width: 280px"
              mode="multiple"
            >
              <!-- <a-select-option v-for="item in renyuanList" :key="item.zname" :value="item.zname">
                {{ item.fullname }}
              </a-select-option> -->

              <a-select-option v-for="item in renyuanList" :key="item.number" :value="item.number">
                {{ item.fullname }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
        <template #title>
          <div ref="modalTitleRef" style="width: 100%; cursor: move"
            ><plus-circle_outlined two-tone-color="#eb2f96" /><span style="padding: 10px 10px"
              >添加任务</span
            ></div
          >
        </template>
        <template #modalRender="{ originVNode }">
          <div>
            <component :is="originVNode" />
          </div>
        </template>
      </a-modal>



       <!-- 销账任务 -->
      <a-modal
        ref="modalRef"
        v-model:visible="taskopen1"
        :modal-style="{ top: '20%', transform: 'translateY(-20%)' }"
        :auto-adjust="false"
        :wrap-style="{ overflow: 'hidden' }"
        width="60%"
        :footer="null"
      >
        <template #title>
          <div ref="modalTitleRef" style="width: 100%; cursor: move"
            ><plus-circle_outlined two-tone-color="#eb2f96" /><span style="padding: 10px 10px"
              >交叉互查核验销账情况</span
            ></div
          >
        </template>

         <a-form
          :model="formStateXZ"
          name="basic"
            :label-col="{ span: 2 }"  
           :wrapper-col="{ span: 25 }" 
          autocomplete="off"
          @finish="onFinish"
          
        >
          <a-form-item label="请选择轮次"  style="margin: 10px 0px">
            <a-select
              v-model:value="formStateXZ.taskpch"
              placeholder="请选择轮次"
              style="width: 280px"
              @change="onChangePch2"
            >
              <a-select-option v-for="item in pchList" :key="item.pch" :value="item.pch">
                {{ item.pch }}
              </a-select-option>
            </a-select>
             &nbsp;&nbsp;&nbsp;&nbsp;
             <a-space class="search-btn">
                <a-button type="primary" @click="onChangePch2">查询</a-button>
             </a-space>
              &nbsp;&nbsp;&nbsp;&nbsp;
              <a-space type="primary" size="small" >
               <a-button type="primary" @click="handleXZExport">导出销账情况</a-button>
             </a-space>
          </a-form-item>

        
          <a-table
            :dataSource="tableData1"
            :columns="displayColumns2"
            :pagination="false"
            :scroll="{ x: 1500, y: detailTableHeight }"
            bordered
          />
         </a-form>


      </a-modal>
      <div class="pagination" style="float: right">
        <div style="float: left; line-height: 32px; padding-right: 12px">共{{ total }}条记录</div>
        <a-pagination
          show-size-changer
          show-total
          v-model:current="pageIndex"
          v-model:pageSize="pageSize"
          :total="total"
          style="float: right"
          @show-size-change="onShowSizeChange"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import moment from 'moment';
import dayjs from 'dayjs';
import { ref, reactive, toRefs, onMounted, onBeforeMount, computed, watch, toRaw } from 'vue';
import { getTasklist, getRegion } from '/@/api/demo/api';
import { useUserStore } from '/@/store/modules/user';
import { useRouter } from 'vue-router';
import { iTableData, iTableColumns } from './types/table';
import { useCheckStore } from '/@/store/modules/checkStore';
import { downloadByUrl } from '/@/utils/file/download';
import { getCqInfo, getZulist, saveTask, getYearRound,deleteTask,getXZList } from '/@/api/demo/api';
import { message, Modal } from 'ant-design-vue';
import { Form } from 'ant-design-vue';
const userStore = useUserStore();
const useForm = Form.useForm;
interface FormState {
  taskname: string; //任务名称
  taskpch: string; //选择轮次
  taskregion: string[];
  cqcs: string[];
  fwcount: number;
  fwzcount: number;
  twofwzcount: number;
  twofwcount: number;
  sycount: number;
  cqbl: string;
  cqcount: string;
  //selectedJb: '2';

  zname: string[];
}
interface FormStateXZ {
  taskpch: string;
}
const formRef = ref();
const labelCol = { span: 5 };


const wrapperCol = { span: 13 };
const formState = reactive<FormState>({
  taskname: '', //任务名称
  taskpch: '', //第一轮
  taskregion: [],
  cqcs: ['1', '2', '3'],
  fwcount: 0,
  fwzcount: 0,
  twofwzcount: 0,
  twofwcount: 0,
  sycount: 0,
  cqbl: '',
  cqcount: '',
  //selectedJb: '2',
  zname: [],
});
const formStateXZ = reactive<FormStateXZ>({
  taskpch: '', 
});
const rules = {
  taskpch: [{ required: true, message: '请选择轮次' }],
  taskname: [{ required: true, message: '请输入任务名称' }],
  //taskregion: [{ required: true, message: '请选择任务区域' }],
  //cqcs: [{ required: true, message: '请输入任务层数' }],
  cqbl: [{ required: true, message: '请输入抽取比例' }],
  cqcount: [{ required: true, message: '请输入抽取房屋数量' }],
  zname: [{ required: true, message: '请选择指派组' }],
};

let userInfo = ref<any>(null);
const router = useRouter();
const zpname = ref<string>(''); //指派组姓名
const txtKeyWord = ref<string>(''); //关键字
const selectpc = ref<string>('第二轮'); //关键字

const floor = ref<string[]>([]); //层数
let detailTableHeight = ref<number>(800); // 表格高度
let tableHeight = ref<number>(0); // 表格高度
const dateFormat = 'YYYY-MM-DD';
const startDate = ref<any>(null); // 开始时间
const endDate = ref<any>(null); // 结束时间
 const checked = ref(false);
let isShowButton = ref(true); //显示
let isShowXZ = ref(true); //显示

const taskopen = ref(false);
const taskopen1 = ref(false);
let pageIndex = ref(1);
let pageSize = ref(15);
const strXzqm = ref<string[]>([]);
let regionList = ref<any[]>([]);
let renyuanList = ref<any[]>([]);
let pchList = ref<any[]>([]);
let total = ref(0);
const store = useCheckStore();
const modalTitleRef = ref<HTMLElement>(null);
const { startTime, endTime } = store.formData || {};
import { useGlobSetting } from '/@/hooks/setting';

    const disabledFutureDate = (current) => {
  return current && current > moment().endOf('day');
};
const globSetting = useGlobSetting();
const valuezp = ref<string[]>([]);
let data = reactive<{
  tableData: iTableData[];
  tableColumns: iTableColumns[];
  wscolsList: { wch: number }[];
  id: number | any;
  loading: Boolean;
  keyWorld: String;
  currentqx: string; // 当前行政区名称
  currentTitle: string;

  cityToken: string | any;
  startTime: string;
  endTime: string;
}>({
  // 表格数据
  tableData: [],
  tableColumns: [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      width: 80,
    },
    {
      title: '任务轮次',
      dataIndex: 'pch',
      key: 'pch',
      align: 'center',
      width: 80,
    },
    {
      title: '任务名称',
      dataIndex: 'taskname',
      key: 'taskname',
      align: 'center',
      width: 120,
      customCell: (row, index, column) => {
        let isNoHzyh = row.full_region !== '汇总' ? true : false;
        let style = 'cursor:pointer;text-decoration: underline; color: blue;';
        let isNoZero = row[column.key] !== 0 ? true : false;
        return {
          style: `${isNoHzyh === true && isNoZero ? style : ''}`,
          class: 'cell-hover',
          onClick: async () => {
            getDetailData(row, index, column, isNoHzyh, isNoZero);
          },
        };
      },
    },
    {
      title: '抽检地区',
      dataIndex: 'full_region',
      key: 'full_region',
      align: 'center',
      width: 100,
    },
    // {
    //   title: '抽检层数',
    //   dataIndex: 'cs',
    //   key: 'cs',
    //   align: 'center',
    //   width: 100,
    // },
    // {
    //   title: '抽检比例',
    //   dataIndex: 'cqbl',
    //   key: 'cqbl',
    //   align: 'center',
    //   width: 80,
    // },
    {
      title: '实际抽检栋数',
      dataIndex: 'cqcount1',
      key: 'cqcount1',
      align: 'center',
      width: 80,
    },
    {
      title: '涉及村数量',
      dataIndex: 'villagecount',
      key: 'villagecount',
      align: 'center',
      width: 100,
      customCell: (row, index, column) => {
        let isNoHzyh = row.full_region !== '汇总';
        let isNoZero = row[column.key] !== 0;
    
    // 只有当不是汇总行且值不为0时才可点击
     if (isNoHzyh && isNoZero) {
        let style = 'cursor:pointer;text-decoration: underline; color: blue;';
        return {
            style: style,
            class: 'cell-hover',
            onClick: async () => {
                getDetailData_2(row, index, column, isNoHzyh, isNoZero);
            },
        };
    }
    
    // 其他情况返回空对象或只有样式
    return {
        style: '',
        class: '',
    };
      },
    },

    // {
    //   title: '指派组',
    //   dataIndex: 'zname',
    //   key: 'zname',
    //   align: 'center',
    //   width: 150,
    // },
    {
      title: '指派人员',
      dataIndex: 'taskrysname',
      key: 'taskrysname',
      align: 'center',
      width: 150,
    },

    // {
    //   title: '可抽检栋数',
    //   dataIndex: 'zcount',
    //   key: 'zcount',
    //   align: 'center',
    //   width: 100,
    // },
    // {
    //   title: '剩余栋数',
    //   dataIndex: 'sycount',
    //   key: 'sycount',
    //   align: 'center',
    //   width: 100,
    // },
    {
      title: '抽检时间',
      dataIndex: 'time',
      key: 'time',
      align: 'center',
      width: 150,
    },
    {
      title: '已核验数量',
      dataIndex: 'hycount',
      key: 'hycount',
      align: 'center',
      width: 100,
         customCell: (row, index, column) => {
        let isNoHzyh = row.full_region !== '汇总';
        let isNoZero = row[column.key] !== 0;
    
    // 只有当不是汇总行且值不为0时才可点击
     if (isNoHzyh && isNoZero) {
        let style = 'cursor:pointer;text-decoration: underline; color: blue;';
        return {
            style: style,
            class: 'cell-hover',
            onClick: async () => {
                getDetailData_1(row, index, column, isNoHzyh, isNoZero);
            },
        };
    }
    
    // 其他情况返回空对象或只有样式
    return {
        style: '',
        class: '',
    };
      },
    },
    {
      title: '未核验数量',
      dataIndex: 'whycount',
      key: 'whycount',
      align: 'center',
      width: 100,
        customCell: (row, index, column) => {
        let isNoHzyh = row.full_region !== '汇总';
        let isNoZero = row[column.key] !== 0;
    
    // 只有当不是汇总行且值不为0时才可点击
     if (isNoHzyh && isNoZero) {
        let style = 'cursor:pointer;text-decoration: underline; color: blue;';
        return {
            style: style,
            class: 'cell-hover',
            onClick: async () => {
                getDetailData_3(row, index, column, isNoHzyh, isNoZero);
            },
        };
    }
    
    // 其他情况返回空对象或只有样式
    return {
        style: '',
        class: '',
    };
      },
    },
    //   {
    //   title: '合格数量',
    //   dataIndex: 'ydb',
    //   key: 'ydb',
    //   align: 'center',
    //   width: 100
    // },
    // {
    //   title: '合格率',
    //   dataIndex: 'dbl',
    //   key: 'dbl',
    //   align: 'center',
    //   width: 100
    // },
    {
      title: '双通道不合格数量',
      dataIndex: 'wdb',
      key: 'wdb',
      align: 'center',
      width: 100,
         customCell: (row, index, column) => {
        let isNoHzyh = row.full_region !== '汇总';
        let isNoZero = row[column.key] !== 0;
    
    // 只有当不是汇总行且值不为0时才可点击
      if (isNoHzyh && isNoZero) {
        let style = 'cursor:pointer;text-decoration: underline; color: blue;';
        return {
            style: style,
            class: 'cell-hover',
            onClick: async () => {
                getDetailData_5(row, index, column, isNoHzyh, isNoZero);
            },
        };
    }
    
    // 其他情况返回空对象或只有样式
    return {
        style: '',
        class: '',
    };
      },
    },
    {
      title: '双通道不合格率',
      dataIndex: 'wdbl',
      key: 'wdbl',
      align: 'center',
      width: 100
    },
     {
      title: '其他不合格数量',
      dataIndex: 'qtwdb',
      key: 'qtwdb',
      align: 'center',
      width: 100,
         customCell: (row, index, column) => {
        let isNoHzyh = row.full_region !== '汇总';
        let isNoZero = row[column.key] !== 0;
    
    // 只有当不是汇总行且值不为0时才可点击
     if (isNoHzyh && isNoZero) {
        let style = 'cursor:pointer;text-decoration: underline; color: blue;';
        return {
            style: style,
            class: 'cell-hover',
            onClick: async () => {
                getDetailData_4(row, index, column, isNoHzyh, isNoZero);
            },
        };
    }
    
    // 其他情况返回空对象或只有样式
    return {
        style: '',
        class: '',
    };
      },
    },
    {
      title: '其他不合格率',
      dataIndex: 'qtwdbl',
      key: 'qtwdbl',
      align: 'center',
      width: 100
    },
    {
      title: '操作',
      align: 'center',
      width: 150,
      customCell: (row) => {

        if (row.full_region === "汇总") {
    return {
      innerHTML: "", // 返回空内容
      onClick: null // 不设置点击事件
    };
  }

        return {
          innerHTML: `<span style="color:blue;cursor: pointer;">删除</span>
                        <span style="color:green;cursor:pointer;">导出明细</span>`,
          onClick: async (event) => {
            // 检查点击的是哪个按钮
            if (event.target.innerText === '删除') {
              //确定删除
              await deleteRowTask(row);
            } else if (event.target.innerText === '导出明细') {
              await exportDetails(row);
            }
          },
        };
      },
    },
  ],
  id: null,
  loading: true,
  keyWorld: '',
  cityToken: '', // 判断是不是市区 110000 是北京市 展示搜索宽
  currentqx: '', // 当前行政区名称
  currentTitle: '', // 当前详情标题
  wscolsList: [{ wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }],
  endTime: '',
  startTime: '',
});
// 表格的 ref Dom名称
let { tableData, loading } = toRefs(data);


let data2 = reactive<{
  tableData1: iTableData[];
  tableColumns1: iTableColumns[];
}>({

   tableData1: [],
  tableColumns1: [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      width: 50,
    },
    {
      title: '行政区',
      dataIndex: 'xzq',
      key: 'xzq',
      align: 'center',
      width: 80,
    },
     {
      title: '行政区代码',
      dataIndex: 'xzqdm',
      key: 'xzq',
      align: 'center',
      width: 80,
    },
    {
      title: '抽检数量',
      dataIndex: 'zcount',
      key: 'zcount',
      align: 'center',
      width: 80,
    },
    {
      title: '已核验数量',
      dataIndex: 'yhycount',
      key: 'yhycount',
      align: 'center',
      width: 80,
    },
    {
      title: '双通道不合格数量',
      dataIndex: 'bhgcount',
      key: 'bhgcount',
      align: 'center',
      width: 80,
    },
    {
      title: '销账数量',
      dataIndex: 'xzcount',
      key: 'xzcount',
      align: 'center',
      width: 80,
    },
    {
      title: '未销账数量',
      dataIndex: 'sycount',
      key: 'sycount',
      align: 'center',
      width: 80,
    }
  ],
});
let { tableData1 } = toRefs(data2);

async function getData() {
  let params = {
    pageIndex: pageIndex.value,
    pageSize: pageSize.value,
    txtKeyWord: txtKeyWord.value,
    pch: selectpc.value,
  };
  loading.value = true;
  let res: any = await getTasklist(params);
  
   if (res || res.items.length > 0) {
      loading.value = false;
      // console.log('data', data);
      // 算列和
      let cqcount1 = total1(res.items, 'cqcount1');
      let villagecount = total1(res.items, 'villagecount');
      let hycount = total1(res.items, 'hycount');
      let whycount = total1(res.items, 'whycount');
      let wdb = total1(res.items, 'wdb');
      let index_count = res.items.length + 1;
      let wdbl = (wdb / hycount * 100).toFixed(2) + '%';
      let qtwdb = total1(res.items, 'qtwdb');
      let qtwdbl = (!hycount || isNaN(hycount)) ? '0%' : (qtwdb / hycount * 100).toFixed(2) + '%';

      let allObj = {
        full_region: '汇总',
        cqcount1: cqcount1,
        villagecount: villagecount,
        hycount: hycount,
        whycount: whycount,
        wdb: wdb,
        index: index_count,
        wdbl: wdbl,
        qtwdb:qtwdb,
        qtwdbl:qtwdbl
      };
      data.tableData = [...res.items, allObj];
      //data.tableData = [...res.items];
       total.value = res.total;
    }
  // 计算总数的方法
  function total1(arr: any, item: any) {
    let total = arr.reduce((pre: any, cur: any) => {
      return parseInt(pre) + parseInt(cur[item]);
    }, 0);
    return total;
  }
  //data.tableData = [...res.items];
 
  loading.value = false;
}

async function getRound() {
  let res: any = await getYearRound();
  if (res.total > 0) {
    pchList.value = res.items;
    formState.taskpch = res.items[0].pch;

    onChangePch(formState.taskpch);
  } else {
    message.error('请先新建本年度轮次');
    return;
  }
}

async function getRound1() {
  let res: any = await getYearRound();
  if (res.total > 0) {
    pchList.value = res.items;
    formStateXZ.taskpch = res.items[0].pch;

    onChangePch2(formStateXZ.taskpch);
  } else {
    message.error('请先新建本年度轮次');
    return;
  }
}
async function exportDetails(row) {
  const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;
  const tk = userStore.getToken;
  downloadByUrl({
    url:
      uriBase +
      '/static/task/taskExportbytaskid?access_token=' +
      tk +
      '&taskid=' +
      row.id +
      '&taskname=' +
      row.taskname,
    target: '_blank',
  });
}

async function deleteRowTask(row) 
{
  let params = {
    taskid: row.id + '',
    taskname: row.taskname,
  };
  if (row.hycount == 0) {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除此任务吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try 
        {
         let res: any = await deleteTask(params);
         if(res.total>0)
         {
            message.success('删除成功！');  
            getData();
         }
        } catch (error) {
          message.error('删除失败，请重试！');
        }
      },
    });
  }
}
function handleHourseExport() 
{
  
    const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;
    const tk = userStore.getToken;
    downloadByUrl({
      url:
        uriBase +
        '/static/task/taskExportALL?access_token=' +
        tk +
         '&pch=' +
        selectpc.value +
         '&cked=' +
        checked.value +
        '&startTime=' +
        startDate.value.format('YYYY-MM-DD') +
        '&endTime=' +
        endDate.value.format('YYYY-MM-DD'),
      target: '_blank',
    });
  }

function handleXZExport() 
{
  
    const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;
    const tk = userStore.getToken;
    downloadByUrl({
      url:
        uriBase +
        '/static/task/taskExportXZ?access_token=' +
        tk +
         '&pch=' +
        formStateXZ.taskpch,
      target: '_blank',
    });
  }

function btnTaskXZ() {
  taskopen1.value = true;
  getRound1(); //获取轮次信息




}

function showModal() {
  taskopen.value = true;
  formState.taskname = '';
  formState.taskregion = [];
  formState.cqbl = '';
  formState.cqcount = '';
  formState.sycount = 0;
  formState.cqcs = ['1', '2', '3'];
  renyuanList.value = [];
  formState.zname = [];
  getRound(); //获取轮次信息
  getInfo(); //获取扣除信息
}
const handleOk = () => {
  //loading.value = true;
  setTimeout(() => {
    //loading.value = false;
    taskopen.value = false;
  }, 100);
};
//下钻 任务下所有房子
const getDetailData = async (row: any) => {
  let params = {
    xzqdm: row.xzqdm,
    taskid: row.id + '',
    currentTitle: '【' + row.taskname + '】核验情况',
  };
  store.setData(params); // 存入Pinia
  router.push({
    path: 'sampling/taskhourselist',
    query: { showSelect: 'true' }, // 参数必须是字符串
  });
};
//下钻 任务下已核验房子
const getDetailData_1 = async (row: any) => {
  debugger;
  let params = {
    xzqdm: row.xzqdm,
    taskid: row.id + '',
    hyzt2: '已核验',
    currentTitle: '【' + row.taskname + '】已核验情况',
  };
  console.log('111', params);
  store.setData(params); // 存入Pinia
  router.push({
    path: 'sampling/taskhourselist',
    query: { showSelect: 'false' }, // 参数必须是字符串
  });
};

const getDetailData_5 = async (row: any) => {
  debugger;
  let params = {
    xzqdm: row.xzqdm,
    taskid: row.id + '',
    hyzt2: '已核验',
    currentTitle: '【' + row.taskname + '】已核验不合格情况',
    jsrysstd:"否"
  };
  console.log('111', params);
  store.setData(params); // 存入Pinia
  router.push({
    path: 'sampling/taskhourselist',
    query: { showSelect: 'false' }, // 参数必须是字符串
  });
};

//下钻 任务下未核验房子
const getDetailData_3 = async (row: any) => {
  let params = {
    xzqdm: row.xzqdm,
    taskid: row.id + '',
    hyzt2: '未核验',
    currentTitle: '【' + row.taskname + '】未核验情况',
  };
  store.setData(params); // 存入Pinia
  router.push({
    path: 'sampling/taskhourselist',
    query: { showSelect: 'false' }, // 参数必须是字符串
  });
};

const getDetailData_4 = async (row: any) => {
  let params = {
    xzqdm: row.xzqdm,
    taskid: row.id + '',
    currentTitle: '【' + row.taskname + '】其他不合格明细',
  };
  store.setData(params); // 存入Pinia
  router.push({
    path: 'sampling/taskbhglist',
    query: { showSelect: 'false' }, // 参数必须是字符串
  });
};
//下钻
const getDetailData_2 = async (row: any) => {
  let params = {
    xzqdm: row.xzqdm,
    taskid: row.id + '',
    taskname: row.taskname,
    currentTitle: '【' + row.taskname + '】抽检村庄情况',
  };
  store.setData(params); // 存入Pinia
  router.push({
    path: 'sampling/taskcunlist',
  });
};
watch(pageSize, () => {
  // console.log('pageSize', pageSize.value);
  getData();
});
watch(pageIndex, () => {
  // console.log('current', pageIndex.value);
  getData();
});
async function handleJbChange() {}
async function getInfo() {
  let params: any = {
    xzqdm: '',
    towndm: '',
    villagedm: '',
    cs: '',
    pch: '',
  };
  if (formState.taskregion != undefined && formState.taskregion.length != 0) {
    params.xzqdm = formState.taskregion[0];
    params.towndm = formState.taskregion[1];
    params.villagedm = formState.taskregion[2];
  }

  if (formState.cqcs != undefined && formState.cqcs.length != 0) {
    params.cs = formState.cqcs + '';
  }
  params.pch = formState.taskpch;
  debugger;
  let res: any = await getCqInfo(params);
  if (res != null) {
    formState.fwcount = res.pageTotal;
    formState.fwzcount = res.total;
    formState.sycount = formState.fwcount;
    formState.twofwzcount = res.items[0];
    formState.twofwcount = res.items[1];
    if (formState.cqcount != '' && formState.cqbl != '') {
      formState.cqcount = Math.floor((parseInt(formState.fwzcount) * formState.cqbl) / 100);
      formState.sycount = parseInt(formState.fwcount) - parseInt(formState.cqcount);
    }
  }
}
const handleChange = (checkedValues) => {
  // 处理"全部"选项的特殊逻辑
  if (checkedValues.includes('0')) {
    // 如果选择了"全部"，则只保留"全部"选项
    formState.cqcs = ['0'];
  }
  fetchDataWithCsFilter(formState.cqcs);
};
const fetchDataWithCsFilter = (values) => {
  // 构建查询条件
  let condition = '';
  if (!values.includes('0') && values.length > 0) {
    condition = `${values.join(',')}`;
    if (!formState.cqcs.concat(condition)) {
      formState.cqcs.push(condition);
    }
  }
  getInfo();
};
function getTime() {
  data.startTime = moment(startDate.value.$d).format('YYYY-MM-DD');
  data.endTime = moment(endDate.value.$d).format('YYYY-MM-DD');
}
function searchBtn() {
  //getTime();
  data.loading = true;
  getData();
}
const dragTransform = ref('translateX(0)'); // 拖动偏移量
const transformStyle = computed(() => ({
  transform: `translateY(-50%) ${draggingTransform.value}`, // 保留初始的 -50%
  top: '20% !important',
}));

function getUserInfo() {
  const userStore = useUserStore();
  userInfo.value = userStore?.getUserInfo;
  const { role } = userInfo.value;
  if (role === 'Area') {
    isShowButton=false;
    isShowXZ=false;
  } 
}
function handleInput() {
  formState.cqcount = Math.floor((parseInt(formState.fwzcount) * formState.cqbl) / 100);
  formState.sycount = parseInt(formState.fwcount) - parseInt(formState.cqcount);
}
function handleInput2() {
  if (parseInt(formState.fwcount) === 0) {
    formState.cqbl = 0;
  } else {
    formState.cqbl = parseFloat(
      ((parseInt(formState.cqcount) / parseInt(formState.fwzcount)) * 100).toFixed(2),
    );
  }
  formState.sycount = parseInt(formState.fwcount) - parseInt(formState.cqcount);
}
function onChange(value) {
  valuezp.value = value;
  getInfo();
}
function onChangePch(value) {
  getZname();
}
async function onChangePch2(value) {
  //获取销账情况
  let params = {
    pch:value,
  };
  let res: any = await getXZList(params);
  data2.tableData1 = [...res.items];
}
async function getZname() {
  let params: any = {
    pch: formState.taskpch,
  };
  let res: any = await getZulist(params);
  renyuanList.value = res.items;
}
const displayColumns = computed(() => {
  const { role } = userInfo.value;
  let arr: any[] = [];
  if (role === 'City') {
    // qx
    arr = data.tableColumns.filter((item) => item.key !== 'jzmc' && item.key !== 'czmc');
    return arr;
  } else if (role === 'Area') {
    // jz
    arr = data.tableColumns.filter((item) => item.key !== 'czmc' && item.key !== 'qxmc');
    return arr;
  } else if (role === 'Street') {
    // cun
    arr = data.tableColumns.filter((item) => item.key !== 'jzmc' && item.key !== 'qxmc');
    return arr;
  } else {
    return data.tableColumns;
  }
});
const displayColumns2 = computed(() => {
 return data2.tableColumns1;
});
async function getRegionData() {
  let res: any = await getRegion();
  regionList.value = res;
}
const getTableHeight = () => {
  setTimeout(() => {
    detailTableHeight.value = window.innerHeight - 182;
    tableHeight.value = window.innerHeight - 292;
  });
};
async function validateForm() {
  loading.value = true;
  formRef.value
    .validate()
    .then(async () => {
      let params: any = {
        taskname: '',
        cqcount: '',
        cqbl: '',
        xzqdm: '',
        towndm: '',
        villagedm: '',
        cs: '',
        fwcount: '',
        pch: '',
        zname: '',
      };
      params.taskname = formState.taskname;
      params.cqcount = formState.cqcount;
      console.log('2222', formState.cqbl);
      params.cqbl = formState.cqbl + '%';
      params.fwcount = formState.fwcount;
      params.sycount = formState.sycount;
      if (formState.taskregion != undefined && formState.taskregion.length != 0) {
        params.xzqdm = formState.taskregion[0];
        params.towndm = formState.taskregion[1];
        params.villagedm = formState.taskregion[2];
      }
      if (formState.cqcs != undefined && formState.cqcs.length != 0) {
        params.cs = formState.cqcs + '';
      }
      params.pch = formState.taskpch;
      params.zname = formState.zname + '';
      let res: any = await saveTask(params);
      if (res.total > 0) {
        debugger;
        message.success('抽检任务添加成功');
        taskopen.value = false;
        getData();
      } else if (res.total == -1) {
        message.error('抽检任务添加失败,未找到指派人员');
        //message.error('抽检任务添加失败,指派组已全部分配任务');
      } else if (res.total == -2) {
        message.error('抽检任务添加失败,随机抽取组人员数量大于抽检房屋数量');
      } else {
        message.error('抽检任务添加失败');
      }
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
      return;
    });
}
onBeforeMount(() => {
  getUserInfo();
});
onMounted(() => {
  getRegionData();
  //getCode();
  if (startDate.value == null) {
      let currentDate = moment().format('YYYY-MM-DD');
      const start: any = dayjs(currentDate).subtract(7, 'day');
      const end: any = dayjs(currentDate);
      startDate.value = start;
      endDate.value = end;
      getTime();
    }
  getData();
  getTableHeight();
});
</script>

  <!-- Add "scoped" attribute to limit CSS to this component only -->
  <style scoped lang="less">
#map {
  height: calc(100vh - 140px);
}

.x-houseMng-search {
  z-index: 100;
  margin: 6px;
  position: absolute;
}

.root-house-mng-main {
  margin: 6px;
}

.x-village-tabs {
  //z-index: 100;
  //position: absolute;
  width: 60vw;
  margin-top: 6px;
  margin-left: 40px;
  //background-color: rgba(34, 34, 34, 0.6);
  :deep(.ant-form) {
    margin-top: 6px;
  }
}
</style>

